package com.huhao.concurrency;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
public class MapExample {
    //200个线程同时执行
    private static int threadTotal = 200;
    private static int clientTotal = 5000;

    private static Map<Integer, Integer> map = Maps.newHashMap();

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        for (int index = 0; index < clientTotal; index++) {
            final int threadNum = index;
            exec.execute(() -> {
                try {
                    semaphore.acquire();
                    func(threadNum);
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception", e);
                    e.printStackTrace();
                }
            });
        }
        exec.shutdown();
        log.error("count:{}", map.size());//count:4890
    }

    private static void func(int threadNum) {
        map.put(threadNum, threadNum);
    }
}
